package com.woniuxy.shop.servelet.manager;

import java.io.IOException;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.alibaba.fastjson.JSON;
import com.woniuxy.shop.entity.Admin;
import com.woniuxy.shop.entity.ResponseEntity;
import com.woniuxy.shop.exception.SameAccountException;
import com.woniuxy.shop.exception.ServiceException;
import com.woniuxy.shop.service.AdminService;
import com.woniuxy.shop.service.ServiceProxyFactory;
import com.woniuxy.shop.utils.ShopUtils;

/**
 * Servlet implementation class CateGoryServelet
 */
@WebServlet("/manager/Adminservlet")
public class AdminServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	AdminService as = ServiceProxyFactory.getProxy(AdminService.class);
	AdminService as1 = new AdminService();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
//		request.setCharacterEncoding("utf-8");// 获取参数前指定编码
//		response.setCharacterEncoding("utf-8");
		String opr = request.getParameter("opr");
		if ("add".equals(opr)) {
			doAdd(request, response);
		} else if ("queryAccount".equals(opr)) {
			doQueryAccount(request, response);
		} else if ("query".equals(opr)) {
			doQuery(request, response);
		} else if ("del".equals(opr)) {
			doDel(request, response);
		} else if ("login".equals(opr)) {
			doLogin(request, response);
		} else if ("list".equals(opr)) {
			doList(request, response);
		} else if ("initupdate".equals(opr)) {
			doInitupdate(request, response);
		} else if ("logout".equals(opr)) {
			doLogout(request, response);
		} else if ("tologin".equals(opr)) {
			doTologin(request, response);
		} else if ("update".equals(opr)) {
			doUpdate(request, response);
		} else if ("queryAccount2".equals(opr)) {
			doQueryAccount2(request, response);// 基于原生ajax查账号是否重复
		} else if ("updatePwd".equals(opr)) {
			doUpdatepwd(request, response);
		} else if ("upavarta".equals(opr)) {
			doUpavarta(request, response);
		}

	}

	private void doUpavarta(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		System.out.println("df");
		ResponseEntity<String> rese = new ResponseEntity<String>();
		try {
			Part p = request.getPart("sdata");
			String imgname = p.getName();
			System.out.println(imgname);
			if (imgname.equals("")) {
				rese.setCode(102);
				rese.setMsg("error");
				ShopUtils.write(response, rese);
				return;
			}
			String path = getServletContext().getRealPath("/images/goods");
			// 产生一个唯一的文件名
			String fileName = UUID.randomUUID().toString().replaceAll("-", "");
			p.write(path + "/" + fileName);
			String image = "images/goods/" + fileName;
			rese.setCode(200);
			rese.setData(image);
			rese.setMsg("ok");
			ShopUtils.write(response, rese);
		} catch (Exception e) {
			rese.setCode(500);
			rese.setMsg("error");
			ShopUtils.write(response, rese);
		}
	
		
	}

	private void doUpdatepwd(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String oldPwd = request.getParameter("oldPwd");
		System.out.println(oldPwd);
		String newPwd = request.getParameter("newpwd");
		System.out.println(newPwd);
		Enumeration<String> names = request.getSession().getAttributeNames();
		while (names.hasMoreElements()) {
			String name = names.nextElement();
			Object value = request.getSession().getAttribute(name);
			System.out.println(name + "->" + value);
		}
		Admin a = (Admin) request.getSession().getAttribute("admin");
		ResponseEntity<Void> rese = new ResponseEntity<Void>();
		if (!oldPwd.equals(a.getPassword())) {
			rese.setCode(101);
			rese.setMsg("密码不正确");
		} else {
			try {
				as.updatePwd(a.getAccount(), newPwd);
				rese.setCode(200);
				rese.setMsg("ok");
			} catch (ServiceException e) {
				rese.setCode(500);
				rese.setMsg("fail");
			}
		}
		System.out.println(rese.getCode());
		ShopUtils.write(response, rese);

	}

	private void doQueryAccount2(HttpServletRequest request, HttpServletResponse response) throws IOException {
		ResponseEntity<Boolean> rese = new ResponseEntity<Boolean>();
		String act = request.getParameter("account");
		try {
			int len = as.judgeAccountrName(act);
			rese.setCode(200);
			rese.setMsg("ok");
			if (len == 0) {
				rese.setData(false);
			} else {
				rese.setData(true);
			}
		} catch (ServiceException e) {
			rese.setCode(500);
			rese.setMsg("error");
		}
		response.getWriter().write(JSON.toJSONString(rese));
	}

	/**
	 * 修改管理员信息
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	private void doUpdate(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String role = request.getParameter("role");
		String status = request.getParameter("status");
		String sid = request.getParameter("id");
		// 对数据有效性进行校验
		// 账号校验
		String account = request.getParameter("name");
		if (account == null || account.trim().equals("")) {
			request.setAttribute("msg1", "账号不能为空");
			request.getRequestDispatcher("admin/admin_update.jsp").forward(request, response);
			return;
		}
		if (account.length() < 2 || account.length() > 15) {
			request.setAttribute("msg1", "账号长度必须在2-15位");
			request.getRequestDispatcher("admin/admin_update.jsp").forward(request, response);
			return;
		}
		// 密码校验
		String pwd = request.getParameter("pwd");
		if (pwd == null || pwd.trim().equals("")) {
			request.setAttribute("msg2", "密码不能为空");
			request.getRequestDispatcher("admin/admin_update.jsp").forward(request, response);
			return;
		}
		if (pwd.length() < 3 || pwd.length() > 15) {
			request.setAttribute("msg2", "密码长度必须在3-15位");
			request.getRequestDispatcher("admin/admin_update.jsp").forward(request, response);
			return;
		}
		// 确认密码校验
		String repwd = request.getParameter("repwd");
		if (!pwd.equals(repwd)) {
			request.setAttribute("msg3", "密码不一致");
			request.getRequestDispatcher("admin/admin_update.jsp").forward(request, response);
			return;
		}

		// 更新值
		try {
			Admin a = as.getAdminById(Integer.parseInt(sid));
			if (!a.getAccount().equals(account)) {
				Admin temp = as.getAdmin(account);
				if (temp != null) {
					request.setAttribute("msg1", "该账号：" + account + "已被使用");
					request.getRequestDispatcher("admin/admin_update.jsp").forward(request, response);
					return;
				} else {
					a.setAccount(account);
				}
			}
			a.setPassword(pwd);
			a.setStatus(status);
			a.setRole(role);
			as.update(a);
		} catch (ServiceException e) {
			request.setAttribute("msg4", "系统维护中,请稍后再试！");
			request.getRequestDispatcher("admin/admin_update.jsp").forward(request, response);
			return;
		}
		request.setAttribute("success", "管理员" + account + "更新成功！");
		request.getRequestDispatcher("admin/admin_update.jsp").forward(request, response);

	}

	private void doTologin(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.getRequestDispatcher("login.jsp").forward(request, response);

	}

	/**
	 * 退出登录
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void doLogout(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 设置session立即失效
		request.getSession().invalidate();
		response.sendRedirect("login.jsp");

	}

	/**
	 * 登录前查询的数据等
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doInitupdate(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String account = request.getParameter("account");
		Admin admin;
		try {
			admin = as.getAdmin(account);
		} catch (ServiceException e) {
			request.setAttribute("error", "系统维护中,请稍后再试！");
			request.getRequestDispatcher("admin/admin_list.jsp");
			return;
		}
		request.setAttribute("admin", admin);
		request.getRequestDispatcher("admin/admin_update.jsp").forward(request, response);
		;

	}

	private void doList(HttpServletRequest request, HttpServletResponse response) throws IOException {

		ResponseEntity<List<Admin>> rese = new ResponseEntity<List<Admin>>();
		try {
			List<Admin> admins = as.getAdmins();
			rese.setCode(200);
			rese.setData(admins);
			rese.setMsg("ok");
		} catch (ServiceException e) {
			rese.setCode(500);
			rese.setMsg("fail");
		}
		String json = JSON.toJSONString(rese);
		System.out.println(json);
		response.getWriter().write(json);
	}

	/**
	 * 登录
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doLogin(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String account = request.getParameter("account");
		String pwd = request.getParameter("password");
		String captcha = request.getParameter("code");
		String cap = (String) (request.getSession().getAttribute("captcha"));
		String isRemember = request.getParameter("isRemember");
		String autologin = request.getParameter("autologin");
		Admin a;
		try {
			a = as.getAdmin(account);
			request.setAttribute("account", account);
			request.setAttribute("password", pwd);
			if (a == null) {
				request.setAttribute("error", "没有账号:" + account);
				request.getRequestDispatcher("login.jsp").forward(request, response);
				return;
			}
			if (pwd == null || !a.getPassword().equals(pwd)) {
				request.setAttribute("error", "密码错误");
				request.getRequestDispatcher("login.jsp").forward(request, response);
				return;
			}
			if (!cap.equals(captcha)) {
				request.setAttribute("msg", "验证码错误");
				request.getRequestDispatcher("login.jsp").forward(request, response);
				return;
			}
		} catch (ServiceException e) {
			request.setAttribute("error", "系统维护中，请稍后再试");
			request.getRequestDispatcher("login.jsp").forward(request, response);
			return;
		}
		// 设置登录的IP和时间
		String ip = ShopUtils.getIpAddr(request);
		String logintime = ShopUtils.getNowTimeWithType();
		try {
			as.setIpTime(a.getId(), ip, logintime);
			;
		} catch (ServiceException e) {
			// 设置IP时出错，怎么处理？暂不处理
		}

		// 实现记住我的功能
		if (isRemember != null) {
			Cookie namecookie = new Cookie("act", account);
			Cookie pwdcookie = new Cookie("pwd", pwd);
			if ("1".equals(isRemember)) {
				namecookie.setMaxAge(60);
				pwdcookie.setMaxAge(60);
			} else if ("2".equals(isRemember)) {
				namecookie.setMaxAge(60 * 60);
				pwdcookie.setMaxAge(60 * 60);
			}
			response.addCookie(namecookie);
			response.addCookie(pwdcookie);
		}
		// 自动登录相关设置
		Cookie cookieAccount = null;
		// 判断是否有设置自动登录
		if (autologin != null) {
			// 如果设置自动登录，将当前账号保存到cookie中
			cookieAccount = new Cookie("account", account);
			response.addCookie(cookieAccount);
		} else {
			// 没有设置自动登录，则循环遍历cookie将name为account的删除掉
			Cookie[] cookies = request.getCookies();
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals("account")) {
					// 只将cookie的maxage设置为0并不能将其删掉，还应将其重新添加
					cookie.setMaxAge(0);
					response.addCookie(cookie);
				}
			}
		}
		request.getSession().setAttribute("admin", a);
		request.getSession().setAttribute("welcome", "欢迎您:" + account + "!");
		response.sendRedirect("index.jsp");

	}

	private void doDel(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		String name = request.getParameter("name");
		List<Admin> admins;
		try {
			as.Del(id);
			admins = as.getAdmins();
		} catch (ServiceException e) {
			request.setAttribute("error", "系统维护中,请稍后再试！");
			request.getRequestDispatcher("Adminservlet?opr=query").forward(request, response);
			return;
		}
		request.setAttribute("admins", admins);
		request.setAttribute("success", "删除" + name + "成功！");
		request.getRequestDispatcher("admin/admin_list.jsp").forward(request, response);
		return;

	}

	private void doQuery(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 待改善，如果此步出错，如何处理？
		List<Admin> admins = as.getAdmins();
		request.setAttribute("admins", admins);
		request.getRequestDispatcher("admin/admin_list.jsp").forward(request, response);

	}

	private void doQueryAccount(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String account = request.getParameter("account");
		String hid = request.getParameter("id");
		String temp = "";
		if (hid != null) {
			temp = as.getAdminById(Integer.parseInt(hid)).getAccount();
		}
		String repeat = "no";
		if (as.judgeAccountrName(account) != 0 && !temp.equals(account)) {
			repeat = "yes";
		}
		response.getWriter().write(repeat);

	}

	private void doAdd(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		Admin a = new Admin();
		// 账号校验
		String account = request.getParameter("name");
		if (account == null || account.trim().equals("")) {
			request.setAttribute("msg1", "账号不能为空");
			request.getRequestDispatcher("admin/admin_add.jsp").forward(request, response);
			return;
		}
		if (account.length() < 2 || account.length() > 15) {
			request.setAttribute("msg1", "账号长度必须在2-15位");
			request.getRequestDispatcher("admin/admin_add.jsp").forward(request, response);
			return;
		}
		// 密码校验
		String pwd = request.getParameter("pwd");
		if (pwd == null || pwd.trim().equals("")) {
			request.setAttribute("msg2", "密码不能为空");
			request.getRequestDispatcher("admin/admin_add.jsp").forward(request, response);
			return;
		}
		if (pwd.length() < 3 || pwd.length() > 15) {
			request.setAttribute("msg2", "密码长度必须在3-15位");
			request.getRequestDispatcher("admin/admin_add.jsp").forward(request, response);
			return;
		}
		// 确认密码校验
		String repwd = request.getParameter("repwd");
		if (!pwd.equals(repwd)) {
			request.setAttribute("msg3", "密码不一致");
			request.getRequestDispatcher("admin/admin_add.jsp").forward(request, response);
			return;
		}

		// 设置属性
		a.setAccount(account);
		a.setPassword(pwd);
		a.setRole("普通管理员");
		a.setStatus("正常");
		try {
			as1.add(a);
		} catch (ServiceException e) {
			if (e.getCause() instanceof SameAccountException) {
				// 提示类别已存在的信息
//				response.getWriter().write("账号"+account+"已存在");
				request.setAttribute("msg1", "账号" + account + "已存在");
				request.getRequestDispatcher("admin/admin_add.jsp").forward(request, response);
				return;
			}
			request.setAttribute("msg4", "系统维护中,请稍后再试！");
			request.getRequestDispatcher("admin/admin_add.jsp").forward(request, response);
			return;
		}
		request.setAttribute("success", "管理员" + account + "添加成功！");
		request.getRequestDispatcher("admin/admin_add.jsp").forward(request, response);

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
